package com.beanbean.mvvmtest.viewmodel;

import com.beanbean.mvvmtest.adapter.ListAdapter;
import com.beanbean.mvvmtest.base.BaseLoadListener;
import com.beanbean.mvvmtest.bean.UserInfo;
import com.beanbean.mvvmtest.model.IListModel;
import com.beanbean.mvvmtest.model.ListModeImpl;
import com.beanbean.mvvmtest.view.IListView;

import java.util.List;

public class ListVM implements BaseLoadListener<UserInfo> {
    private static final String TAG = "ListVM";
    private IListModel mListModel;
    private IListView mListView;
    private ListAdapter mAdapter;
    private int currPage = 1; //当前页数

    public ListVM(IListView listView, ListAdapter adapter) {
        mListView = listView;
        mAdapter = adapter;
        mListModel = new ListModeImpl();
        getNewsData();
    }

    /**
     * 第一次获取新闻数据
     */
    private void getNewsData() {
        mListModel.loadUserData(currPage, this);
    }

    public void loadRefreshData(){
        currPage = 1;
        mListModel.loadUserData(currPage, this);
    }

    /**
     * 加载数据成功
     *
     * @param list
     */
    @Override
    public void loadSuccess(List<UserInfo> list) {
        if (currPage > 1) {
            //上拉加载的数据
            mAdapter.loadMoreData(list);
        } else {
            //第一次加载或者下拉刷新的数据
            mAdapter.refreshData(list);
        }
    }

    /**
     * 加载失败
     *
     * @param message
     */
    @Override
    public void loadFailure(String message) {
        if (currPage > 1) {
            //加载失败需要回到加载之前的页数
            currPage--;
        }
        mListView.loadFailure(message);
    }

    /**
     * 开始加载
     */
    @Override
    public void loadStart() {
        mListView.loadStart();
    }

    /**
     * 加载结束
     */
    @Override
    public void loadComplete() {
        mListView.loadComplete();
    }
}
